import tushare as ts
import pandas as pd
import numpy as np

print(ts.__version__)

# ts.set_token('23ddb2e6cc09200a7263537acb5a532dd76f443966c0b078ee53278d')
ts.set_token('ec10c4e9cdc91d52e6cedaf20a663b510e68d0006e217cae1b43bfb6')
pro = ts.pro_api()

# 数据清洗
gujing = pro.monthly(**{"ts_code": "000596.sz", "start_date": 20000101, "end_date": 20200101, },
                     fields=["trade_date", "close", "vol"])
gujing_date = gujing["trade_date"][::-1]
gujing_close = gujing["close"][::-1]
gujing_vol = gujing["vol"][::-1]
print(gujing.isnull().sum())
# print(any(gujing.isna()))
print(gujing.isna().sum())
# print(any(gujing.isna()))
print(gujing.info())

# 绘制收盘价和成交量的时间序列图
import matplotlib.pyplot as plt

"""需修改x的数据"""
x = gujing_date
"""需修改y的数据"""
y1 = gujing_close
y2 = gujing_vol
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y1, label="close")
ax1.set_ylabel("close price")
ax1.legend(loc=(1.2, 0.8))

ax2 = ax1.twinx()  # this is the important function
ax2.plot(x, y2, "r", label="vol")
ax2.set_ylabel("volume")
ax2.set_xlabel("time")
ax2.legend(loc=(1.2, 0.9))
ax2.set_xticks(np.arange(0, len(x), 35))
ax2.set_xticklabels(x[::30], rotation=90, fontdict={'fontsize': 10})
plt.grid(which='major', axis='x', linewidth=0.75, linestyle='-', color='0.75', dashes=(15, 10))
plt.grid(which='major', axis='y', linewidth=0.75, linestyle='-', color='0.75', dashes=(15, 10))
plt.show()

# 绘制收益率分布图
gujing_close_diff = gujing_close.diff()
gujing_r = gujing_close_diff / gujing_close

fig2 = plt.figure()
plt.rcParams['axes.unicode_minus'] = False  # 显示负号
n, bins, patches = plt.hist(x=gujing_r, bins='auto', color='#0504aa', alpha=0.7, rwidth=0.85)
plt.grid(axis='y', alpha=0.75)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('gujing return')
maxfreq = n.max()
plt.ylim(2)
plt.show()

# 数据分析
import scipy.stats as stats

print(gujing_close.describe())
print(gujing_vol.describe())
print(gujing_r.describe())
np.var(gujing_close)
stats.skew(gujing_close)
gujing_close.kurt()
np.var(gujing_vol)
stats.skew(gujing_vol)
gujing_vol.kurt()
np.var(gujing_r)
stats.skew(gujing_r)
gujing_r.kurt()

"""t检验"""
mean = np.mean(gujing_r)
var = np.var(gujing_r)
T = len(gujing_r)
t = (np.sqrt(T) * mean) / var
p = 2 * (1 - stats.norm.cdf(t))
"""偏度检验"""
s = gujing_r.skew()
ts = s / np.sqrt(6 / T)
p_ts = 2 * (1 - stats.norm.cdf(ts))
"""峰度检验"""
k = gujing_r.kurt()
tk = (k - 3) / np.sqrt(24 / T)
p_tk = 2 * (1 - stats.norm.cdf(tk))
"""正态性检验"""
stats.jarque_bera(gujing_r)
stats.shapiro(gujing_r)